<template>
  <div class="autumn-container">
    <!-- 面包 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/system/account/accountList' }">账户列表</el-breadcrumb-item>
      <el-breadcrumb-item>账户信息</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <div class="autumn-center">
      <div class="edit-form">
        <el-form ref="editFormRef" size="large" label-width="90px" :model="editForm" :rules="editFormRules">
          <el-row>
            <el-col :span="24">
              <el-form-item label="图像">
                <el-upload class="avatar-uploader" accept="image/jpg,image/jpeg,image/gif,image/png"
                  :action="$uploadUrl()" :headers="$headers()" :show-file-list="false"
                  :on-success="handleAvatarSuccess">
                  <img v-if="avatarUrl" :src="avatarUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账号" prop="loginName">
                <el-input v-model="editForm.loginName" :disabled="editForm.id ? true : false" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="editForm.name" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工号" prop="code">
                <el-input v-model="editForm.code" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="editForm.gender">
                  <el-radio :label="'1'">男</el-radio>
                  <el-radio :label="'2'">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属机构" prop="organId">
                <autumn-tree-select size="large" :data="treeOrgans" :defaultKey="editForm.organId"
                  @getValue="getOrganId" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属部门" prop="departIds">
                <autumn-tree-select :multiple="true" size="large" :data="treeDeparts" :defaultKey="departIds"
                  @getValue="getDepartId" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="直系领导" prop="directLeaderName">
                <el-input readonly v-model="editForm.directLeaderName">
                  <template #append>
                    <el-button icon="el-icon-search" @click="showLeaderDialog"></el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="editForm.email" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="phone">
                <el-input v-model="editForm.phone" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所在地区" prop="areaCode">
                <autumn-area v-model="treeAreas"></autumn-area>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="常住地址" prop="address">
                <el-input v-model="editForm.address" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="管理员" prop="isAdmin">
                <el-radio-group v-model="editForm.isAdmin">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" resize="none" v-model="editForm.remark" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div class="form-foot-button">
          <el-button type="primary" @click="submit(editFormRef)">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </div>
    </div>

    <!-- 上级领导 -->
    <account-component :title="'上级领导'" :defaultValue="editForm.directLeader" ref="accountRef" @apply="applyLeader" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { FormInstance } from 'element-plus'
import AccountComponent from '../component/AccountComponent.vue'
import { viewAccount, saveAccount, updateAccount } from 'src/api/system/account'
import { listOrgan } from 'src/api/system/organ'
import { listDepart } from 'src/api/system/department'
import { $previewUrl, $uploadUrl, $headers } from 'src/hooks/useCommon'

const editFormRef = ref<FormInstance>()

// 定义表单数据
const editForm = reactive({
  id: '',
  loginName: '',
  code: '',
  name: '',
  gender: '1',
  organId: '',
  avatar: '',
  email: '',
  phone: '',
  areaCode: '',
  address: '',
  isAdmin: 0,
  remark: '',
  directLeader: '',
  directLeaderName: '',
  departIds: [] as any
})

const editFormRules = {
  loginName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  organId: [
    { required: true, message: '请选择所属机构', trigger: 'blur' }
  ]
}

// 修改时填充表单数据
const treeAreas = ref<string>('')
const avatarUrl = ref<string>('')
const departIds = ref<Array<string>>([])
const route = useRoute()
if (route.query.id) {
  const id = route.query.id as string
  viewAccount(id).then(({ data }) => {
    Object.assign(editForm, data)
    if (data.areaCode) {
      treeAreas.value = data.areaCode
    }
    if (data.avatar) {
      avatarUrl.value = $previewUrl(data.avatar)
    }
    departIds.value = data.departIds
  })
}

watch(treeAreas, (newVal: any, oldVal) => {
  if (!newVal || newVal.length === 0) {
    editForm.areaCode = ''
  } else {
    editForm.areaCode = newVal instanceof Array ? newVal[newVal.length - 1] : newVal
  }
})

// 初始化机构
const treeOrgans = ref<Array<any>>([])
listOrgan().then(({ data }) => {
  treeOrgans.value = data
})

// 初始化部门
const treeDeparts = ref<Array<any>>([])
const initDepart = (organId: string) => {
  listDepart({ organId }).then(({ data }) => {
    treeDeparts.value = data
  })
}
if (route.query.organId) {
  initDepart(route.query.organId as string)
}

const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (!valid) return
    if (!editForm.id) {
      saveAccount(editForm).then(() => {
        cancel()
      })
    } else {
      updateAccount(editForm).then(() => {
        cancel()
      })
    }
  })
}

const router = useRouter()
const cancel = () => {
  router.push('/system/account/accountList')
}

const getOrganId = (val: string) => {
  editForm.organId = val
  initDepart(val)
}

const getDepartId = (val: Array<any>) => {
  editForm.departIds = val
}

function handleAvatarSuccess(res: any) {
  editForm.avatar = res.data.id
  avatarUrl.value = $previewUrl(editForm.avatar)
}

const accountRef = ref()
function showLeaderDialog() {
  accountRef.value.open()
}

const applyLeader = (rows: Array<any>) => {
  const row = rows[0]
  editForm.directLeader = row.id
  editForm.directLeaderName = row.name
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  border: 1px dashed #cccccc;
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>
